package com.lhfeiyu.action.front.other;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.po.AntiqueCity;
import com.lhfeiyu.po.base.BaseProvinceCityArea;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.po.base.BaseUserRelation;
import com.lhfeiyu.service.AntiqueCityService;
import com.lhfeiyu.service.AuthCheckService;
import com.lhfeiyu.service.base.BaseProvinceCityAreaService;
import com.lhfeiyu.service.base.BaseUserRelationService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Result;

@Controller
public class AntiqueCityAction {
	@Autowired
	private AntiqueCityService antiqueCityService;
	@Autowired
	private AuthCheckService authCheckService;
	@Autowired
	private BaseUserRelationService userRelationService;
	@Autowired
	private BaseProvinceCityAreaService provinceCityAreaService;
	
	private static Logger logger = Logger.getLogger("R");
	
	@RequestMapping(value="/antiqueCity")
	public ModelAndView antiqueCity(ModelMap modelMap,HttpSession session
			,@RequestParam(required=false) String r,HttpServletRequest request){
		String path = Page.antiqueCity;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			//User sessionUser = ActionUtil.checkSession4User(session);
			/*if(null == sessionUser){
				return Result.userSessionInvalid(modelMap, "/antiqueCity");
			}*/
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载古玩城页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path,modelMap);
	}
	
	@RequestMapping(value="/addAntiqueCity")
	public ModelAndView addAntiqueCity(ModelMap modelMap,HttpSession session
			,@RequestParam(required=false) String r,HttpServletRequest request){
		String path = Page.addAntiqueCity;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(session);
			if(null == sessionUser){
				String jumpUrl = "/addAntiqueCity";
				if(null != r)jumpUrl += "?r="+r;
				return Result.userSessionInvalid(modelMap, jumpUrl);
			}
			Integer userId = sessionUser.getId();
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("allProvince", 1);
			List<BaseProvinceCityArea> provinceList = provinceCityAreaService.selectListByCondition(map);
			modelMap.put("provinceList", provinceList);
			map.clear();
			map.put("userId", userId);
			map.put("relationType", 64);
			List<BaseUserRelation> userRelationList = userRelationService.selectListByCondition(map);
			if(userRelationList.size() > 0){
				BaseUserRelation userRelation = userRelationList.get(0);
				Integer antiqueCityId = userRelation.getRelationId();
				AntiqueCity antiqueCity = antiqueCityService.selectByPrimaryKey(antiqueCityId);
				modelMap.put("antiqueCity", antiqueCity);
			}
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载添加古玩城页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path,modelMap);
	}
	
	@RequestMapping(value="/antiqueCityDetail/{antiqueCityId}")
	public ModelAndView antiqueCityDetail(ModelMap modelMap,HttpSession session,
			@PathVariable Integer antiqueCityId
			,@RequestParam(required=false) String r,HttpServletRequest request){
		String path = Page.antiqueCityDetail;
		try{
			BaseUser sessionUser = ActionUtil.checkSession4User(session);
			/*if(null == sessionUser){
				return Result.userSessionInvalid(modelMap, "/antiqueCityDetail?antiqueCityId="+antiqueCityId);
			}*/
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			Map<String,Object> map = new HashMap<String,Object>();
			/*map.put("id", antiqueCityId);
			List<AntiqueCity>	antiqueCityList = 	antiqueCityService.selectListByCondition(map);
			if(antiqueCityList.size() > 0){
				AntiqueCity antiqueCity = antiqueCityList.get(0);
				modelMap.put("antiqueCity", antiqueCity);
				modelMap.put("antiqueCityId",antiqueCityId);
			}*/
			AntiqueCity antiqueCity = antiqueCityService.selectByPrimaryKey(antiqueCityId);
			modelMap.put("antiqueCity", antiqueCity);
			modelMap.put("antiqueCityId",antiqueCityId);
			map.clear();
			map.put("allProvince", 1);
			List<BaseProvinceCityArea> provinceList = provinceCityAreaService.selectListByCondition(map);
			modelMap.put("provinceList", provinceList);
			if(null != sessionUser){
				Integer currentUserId = sessionUser.getId();
				map.clear();
				map.put("relationId", antiqueCityId);
				map.put("relationType", 64);
				List<BaseUserRelation> userRelationList = userRelationService.selectListByCondition(map);
				if(userRelationList.size() > 0){
					BaseUserRelation userRelation = userRelationList.get(0);
					Integer userId = userRelation.getUserId();
					modelMap.put("userId", userId);
				}
				modelMap.put("currentUserId", currentUserId);
			}
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载古玩城详情页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path,modelMap);
	}
	
	@RequestMapping(value="/antiqueCityShop/{relationId}")
	public ModelAndView allAntiqueCityShop(ModelMap modelMap,HttpSession session,
			@PathVariable Integer relationId
			,@RequestParam(required=false) String r,HttpServletRequest request){
		String path = Page.antiqueCityShop;
		try{
			/*User sessionUser = ActionUtil.checkSession4User(session);
			if(null == sessionUser){
				return Result.userSessionInvalid(modelMap, "/antiqueCityDetail?relationId="+relationId);
			}*/
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			modelMap.put("relationId", relationId);
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载古玩城商家列表页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path,modelMap);
	}
	
	@ResponseBody
	@RequestMapping(value="/addOrUpdateAntiqueCity" , method=RequestMethod.POST)
	public JSONObject addOrUpdateAntiqueCity(@ModelAttribute AntiqueCity antiqueCity,HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			antiqueCity.setMainStatus(1);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == sessionUser){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = sessionUser.getId();
			String username = sessionUser.getUsername();
			if(null == antiqueCity.getId()){//添加
				if(null == antiqueCity.getCreatedAt()){
					antiqueCity.setCreatedAt(new Date()); 
				}
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("userId", userId);
				map.put("relationType", 64);
				List<BaseUserRelation> userRelationList = userRelationService.selectListByCondition(map);
				if(userRelationList.size() > 0){
					BaseUserRelation userRelation = userRelationList.get(0);
					Integer antiqueCityId = userRelation.getRelationId();
					AntiqueCity aCity = antiqueCityService.selectByPrimaryKey(antiqueCityId);
					if(null != aCity && !"".equals(aCity)){
						json.put("status", "failure");
						json.put("msg", "您的商圈已经存在,请不要重复添加");
						return Result.success(json);
					}
				}
				String serial = CommonGenerator.getSerialByDate("ac");
				antiqueCity.setSerial(serial);
				antiqueCity.setCreatedBy(sessionUser.getUsername());
				antiqueCityService.insert(antiqueCity);
				BaseUserRelation userRelation = new BaseUserRelation();
				userRelation.setUserId(userId);
				userRelation.setRelationType(64);
				userRelation.setRelationId(antiqueCity.getId());
				userRelation.setCreatedAt(new Date());
				userRelation.setUpdatedBy(username);
				userRelationService.insert(userRelation);
				json.put("status", "success");
				json.put("msg", "操作成功");
			}else{//修改
				if(null == antiqueCity.getUpdatedAt()){
					antiqueCity.setUpdatedAt(new Date()); 
				}
				antiqueCity.setUpdatedBy(sessionUser.getUsername());
				antiqueCityService.updateByPrimaryKeySelective(antiqueCity);
				json.put("status", "success");
			}
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_添加或修改古玩城数据出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getAntiqueCityList", method=RequestMethod.POST)
	public JSONObject getAntiqueCityList(HttpServletRequest request) {
		List<AntiqueCity> antiqueCityList = null;
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = ActionUtil.getAllParam(request);
			antiqueCityList = antiqueCityService.selectListByCondition(map);
			Integer total = antiqueCityService.selectCountByCondition(map);
			json.put("rows", antiqueCityList);
			json.put("total", total);
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载古玩城列表出现异常_", json);
		}
		return Result.success(json);
	}
	
}
